package com.lottery.module.service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.lottery.entity.LotteryInfo;
import com.lottery.entity.LotterySaleLog;
import com.lottery.module.dao.LotterySaleLogDao;
import com.lottery.pojo.BuyInfoDto;
import com.lottery.pojo.thrift.service.config.Core;
import com.lottery.thrift.ThriftClient;
import com.lottery.util.FastJsonUtil;
import com.lottery.util.GenerateUtil;

@Service
public class LotterySaleService {

  @Autowired
  private LotterySaleLogDao lotterySaleLogDao;

  @Transactional(propagation = Propagation.SUPPORTS)
  public String buyLottery(String jsonParams) {
    @SuppressWarnings("unchecked")
    Map<String, Object> params = FastJsonUtil.string2BaseBean(jsonParams, Map.class);
    List<BuyInfoDto> buyInfoDtos = FastJsonUtil.string2List(MapUtils.getString(params, "buyInfoDtos"), BuyInfoDto.class);
    String salePlace = MapUtils.getString(params, "salePlace");

    String res = ThriftClient.callService(Core.class, "lotteryInfoService", "findNotEndInfo");
    LotteryInfo lotteryInfo = FastJsonUtil.string2BaseBean(res, LotteryInfo.class);

    String saleLogNo = GenerateUtil.generateBusinessNo();

    for (BuyInfoDto buyInfoDto : buyInfoDtos) {
      LotterySaleLog lotterySaleLog = new LotterySaleLog();
      lotterySaleLog.setSaleLogNo(saleLogNo);
      lotterySaleLog.setLotteryInfoId(lotteryInfo.getId());
      lotterySaleLog.setSaleMoney(new BigDecimal(2));
      lotterySaleLog.setSaleInfo(FastJsonUtil.bean2String(buyInfoDto));
      lotterySaleLog.setSalePlace(salePlace);
      save(lotterySaleLog);
    }
    return "";
  }

  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = RuntimeException.class, readOnly = false)
  public void save(LotterySaleLog lotterySaleLog) {
    lotterySaleLogDao.buy(lotterySaleLog);
  }

}
